package consumer

import (
	"encoding/json"
	"github.com/streadway/amqp"
	"go.uber.org/zap"
	"niu-video/app/consts"
	"niu-video/app/model"
	"niu-video/app/repository"
	"niu-video/pkg/logger"
	"niu-video/pkg/rabbitmq"
)

func registerRelationConsumer() {
	// 新建连接
	rabbit := rabbitmq.NewRabbitMQ(consts.RABBITMQ_RELATION_EXCHANGE, consts.RABBITMQ_RELATION_ROUTE, consts.RABBITMQ_RELATION_QUEUE)
	// 执行消费
	rabbit.Consume(func(d amqp.Delivery) (err error) {
		var relationMessage model.RelationMessage
		if err := json.Unmarshal(d.Body, &relationMessage); err != nil {
			logger.Info("rabbitmq", zap.String("relation", "json解析失败！"))
		}
		switch relationMessage.ActionType {
		case 1:
			err = repository.RelationRepository.Create(&model.Relation{
				FollowingID: relationMessage.FollowingID,
				FollowerID:  relationMessage.FollowerID,
			})
			if err != nil {
				logger.Error("rabbitmq", zap.String("create", err.Error()))
				return err
			}
			repository.UserRepository.UpdateUserFollowCount(relationMessage.FollowerID, 1)
		case 2:
			err = repository.RelationRepository.Delete(relationMessage.FollowingID, relationMessage.FollowerID)
			if err != nil {
				logger.Error("rabbitmq", zap.String("delete", err.Error()))
				return err
			}
			repository.UserRepository.UpdateUserFollowCount(relationMessage.FollowerID, -1)
		}
		return err
	})
}
